import { createRouter, createWebHashHistory, RouteLocationNormalized, NavigationGuardNext } from "vue-router";
import { getToken } from "@/library/utils";
import { useNProgress } from "@/plugins/vue-nprogress";

// 静态路由
import { publicRouter } from "./staticRouter"

import { initDynamicRouter } from "./dynamicRouter";

const { start, done } = useNProgress();

const router = createRouter({
  history: createWebHashHistory(),
  routes: [...publicRouter]
});

// 刷新重新创建路由（防止刷新 404）
await initDynamicRouter(router)

/**
 * @description 路由拦截 —— 路由跳转开始
 * */
router.beforeEach((to: RouteLocationNormalized, from: RouteLocationNormalized, next: NavigationGuardNext) => {
  start();
  if (!getToken().token && to.name !== "login") {
    next("/login");
  } else {
    next();
  }
});

/**
 * @description 路由跳转结束
 * */
router.afterEach((to: RouteLocationNormalized) => {
  done();
  window.scrollTo(0, 0);
});

export default router;